// 帖子和二手可以共用这个评论
import mongoose from 'mongoose';
import moment from 'moment';
import db from './db';
mongoose.Promise = global.Promise;

const BuyGoodSchema = new mongoose.Schema({
    buyGoodId: String, // 商品名
    point: Number, // 积分数
    name: String, // 商品图片
    desc: String,
    url: String, // 商品图片
    code: String, // 券码
    getterId: String,
    createTime: Number,
});

BuyGoodSchema.methods.saveBuyGood = function (buyGood, cb) {
    buyGood.createTime = moment().unix();
    this.model('buyGood').insertMany([buyGood], cb);
};

BuyGoodSchema.methods.getBuyGoods = function (query, cb) {
    const { current, pageSize, ...leftQuery } = query;
    const buyGoodModel = this.model('buyGood');
    buyGoodModel.count(leftQuery, function (err, count) {
        const hasMore = count / pageSize > current;
        buyGoodModel.find(leftQuery).sort({createTime: -1}).skip((current - 1) * pageSize).limit(pageSize).exec((err, buyGoods) => cb(err, buyGoods, count, hasMore));
    });
};

BuyGoodSchema.methods.getAllBuyGoods = function (query, cb) {
    this.model('buyGood').find(query, cb);
};

BuyGoodSchema.methods.getBuyGood = function (query, cb) {
    this.model('buyGood').findOne(query, cb);
};

BuyGoodSchema.methods.updateBuyGood = function (buyGood, cb) {
    const _id = buyGood._id;
    delete buyGood._id;
    this.model('buyGood').findOneAndUpdate({ _id }, { $set: buyGood }, cb);
};

BuyGoodSchema.methods.removeBuyGoods = function (buyGoodIds, cb) {
    this.model('buyGood').remove({ _id: { $in: buyGoodIds } }, cb);
};

export default db.model('buyGood', BuyGoodSchema);